<template>
  <el-row>
    <el-col :span="7" >
      <div class="box" >
        <el-scrollbar>
          <basic-container>
            <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick"/>
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col>
    <el-col :span="17">
      <div v-if="showDevice">
        <basic-container>
          <!--<el-card shadow="hover">
            <div >
              <el-button type="primary" icon="el-icon-search" @click="onclickDevice">查看在线数据</el-button>
            </div>
          </el-card>-->
          <el-form ref="formDevice" :model="formDevice" label-width="100px">
            <el-card shadow="hover">
              <div slot="header">
                <span>设备信息</span>
              </div>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="设备类型">
                    <el-input :disabled="true" v-model="formDevice.deviceTypeName" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="设备型号">
                    <el-input :disabled="true" v-model="formDevice.deviceModel" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="检验状态">
                    <el-input :disabled="true" v-model="formDevice.examStatusName" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="最后检验日期">
                    <el-input :disabled="true" v-model="formDevice.lastDate" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="有效期">
                    <el-input :disabled="true" v-model="formDevice.expiryDate" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="使用地点">
                    <el-input :disabled="true" v-model="formDevice.location" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="安全管理员">
                    <el-input :disabled="true" v-model="formDevice.safetyManager" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="联系方式">
                    <el-input :disabled="true" v-model="formDevice.telephone" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="设备状态">
                    <el-input :disabled="true" v-model="formDevice.deviceStatusName" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="出厂编号">
                    <el-input :disabled="true" v-model="formDevice.madeCode" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="企业自编号">
                    <el-input :disabled="true" v-model="formDevice.selfCode" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="产权证号">
                    <el-input :disabled="true" v-model="formDevice.propertyCode" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="制造单位">
                    <el-input :disabled="true" v-model="formDevice.makeUnit" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="出厂日期">
                    <el-input :disabled="true" v-model="formDevice.factroyDate" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
          </el-form>
        </basic-container>
      </div>
      <div v-if="showPosition">
        <basic-container>
          <el-card shadow="hover">
            <div >
              <el-button type="primary" icon="el-icon-search" @click="onclickPosition">查看在线数据</el-button>
            </div>
          </el-card>
          <el-form ref="formPosition" :model="formPosition" label-width="100px">
            <el-card shadow="hover">
              <div slot="header">
                <span>测点信息</span>
              </div>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="测点位置">
                    <el-input :disabled="true" v-model="formPosition.local" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="测点类型">
                    <el-input :disabled="true" v-model="formPosition.positionTypeName" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="附属设备">
                    <el-input :disabled="true" v-model="formPosition.deviceName" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="测点状态">
                    <el-input :disabled="true" v-model="formPosition.positionStatusName" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="上限预警类型">
                    <el-input :disabled="true" v-model="formPosition.alarmHighTypeName" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="下限预警类型">
                    <el-input :disabled="true" v-model="formPosition.alarmLowTypeName" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="上限预警阈值">
                    <el-input :disabled="true" v-model="formPosition.alarmHighValue" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="下限预警阈值">
                    <el-input :disabled="true" v-model="formPosition.alarmLowValue" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
          </el-form>
        </basic-container>
      </div>
      <div v-if="showAcquisition">
        <basic-container>
          <div>
            <el-radio-group  v-model="radio" size="medium" @change="radioChange">
              <el-radio-button  label="1">通道属性</el-radio-button>
              <el-radio-button  label="2">通道数据</el-radio-button>
            </el-radio-group>
          </div>
        </basic-container>
        <div v-show="showData">
          <basic-container>
            <div class="block">
              <el-row>
                <span class="demonstration">日期范围:  </span>
                <el-date-picker
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  v-model="dateTimerRange"
                  type="datetimerange"
                  :picker-options="pickerOptions"
                  range-separator=" 至 "
                  start-placeholder="开始日期 "
                  end-placeholder=" 结束日期"
                  align="right">
                </el-date-picker>
                <el-button type="primary" @click.native="searchDataRange">查询</el-button>
              </el-row>
            </div>
            <div>
              <el-card>
                <div id="myChartOnlineLine"  ref="myChart" style="height: 400px;"></div>
              </el-card>
            </div>
          </basic-container>
          <basic-container>
            <avue-crud :option="optionTable"
                       :search.sync="search"
                       :data="dataTable"
                       ref="crud"
                       :page.sync="pageTable"
                       @search-change="searchChange"
                       @search-reset="searchReset"
                       @selection-change="selectionChange"
                       @current-change="currentChange"
                       @size-change="sizeChange"
                       @refresh-change="refreshChange"
                       >
            </avue-crud>
          </basic-container>
        </div>
        <div v-show="showProp">
          <basic-container>
            <el-form ref="formSensor" :model="formSensor" label-width="100px">
              <el-card shadow="hover">
                <div slot="header">
                  <span>传感器信息</span>
                </div>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="传感器名称">
                      <el-input :disabled="true" v-model="formSensor.name" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="采集仪">
                      <el-input :disabled="true" v-model="formSensor.parentIdName" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="测点">
                      <el-input :disabled="true" v-model="formSensor.positionIdName" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="传感器类型">
                      <el-input :disabled="true" v-model="formSensor.sensorTypeName" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="传感器别名">
                      <el-input :disabled="true" v-model="formSensor.alias" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="传感器编号">
                      <el-input :disabled="true" v-model="formSensor.code" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="传感器状态">
                      <el-input :disabled="true" v-model="formSensor.statusTypeName" />
                    </el-form-item>
                  </el-col>
                </el-row>

              </el-card>
            </el-form>
          </basic-container>
        </div>
      </div>
    </el-col>
  </el-row>
</template>

<script>
  import {
    getDetail,
    getChannelLazyTree
  } from "@/api/stress/channel";
  import {getList,getAcquisitionOnLine} from "@/api/stress/history";
  import {getDeviceDetail} from "@/api/stress/device";
  import {getPositionDetail} from "@/api/stress/position";
  import {getSensorDetail} from "@/api/stress/sensor";
  import {dateFormat} from "@/util/date";

  export default {
    data() {
      return {
        //显示控制
        showAcquisition: false,
        showPosition: false,
        showDevice: false,
        //设备
        formDevice:{
          deviceType:'',
          deviceTypeName:'',
          deviceModel:'',
          examStatus:'',
          examStatusName:'',
          lastDate:'',
          expiryDate:'',
          location:'',
          safetyManager:'',
          deviceStatus:'',
          deviceStatusName:'',
          telephone:'',
          madeCode:'',
          selfCode:'',
          propertyCode:'',
          factroyDate:'',
        },
        //测点
        formPosition:{
          local:'',
          positionTypeName:'',
          deviceName:'',
          positionStatusName:'',
          alarmHighTypeName:'',
          alarmLowTypeName:'',
          alarmHighValue:'',
          alarmLowValue:'',
          alarmNum:'',
        },
        //传感器
        formSensor:{
          name:'',
          parentIdName:'',
          positionIdName:'',
          sensorTypeName:'',
          code:'',
          alias:'',
          statusTypeName:'',
        },
        //单选框
        radio: "1",
        showProp: false,
        showData: false,
        //表格
        search:{},
        initFlag: true,
        selectionList: [],
        query: {},
        loading: true,
        pageTable: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        optionTable: {
          height: '430px',
          calcHeight: 80,
          tip: false,
          border: true,
          index: true,
          addBtn: false,
          refreshBtn: false,
          showColumn: false,
          columnBtn: false,
          menu: false,
          column: [
            {
              label: "采集时间",
              prop: "startTime",
            },
            {
              label: "采集数值",
              prop: "sampleValue"
            },
            {
              label: "单位",
              prop: "sampleUnit",
              value: "Hz"
            }

          ]
        },
        dataTable: [],
        //关联树
        treeLevel: 0,
        treeId: '',
        props: {
          label: "title",
          value: "key"
        },
        treeData: [],
        treeOption: {
          defaultExpandAll:true,
          nodeKey: 'id',
          lazy: true,
          treeLoad: function (node, resolve) {
            const parentId = (node.level === 0) ? 0 : node.data.value;
            getChannelLazyTree(parentId).then(res => {
              resolve(res.data.data.map(item => {
                return {
                  ...item,
                  leaf: !item.hasChildren
                }
              }))
            });
          },
          addBtn: false,
          menu: false,
          size: 'small',
          props: {
            labelText: '标题',
            label: 'title',
            value: 'value',
            children: 'children'
          }
        },
        //图表数据设置
        pageLine: {
          pageSize: 500,
          currentPage: 1,
          total: 0
        },
        //图表设置
        upColor:'#ec0000',
        upBorderColor: '#8A0000',
        downColor: '#00da3c',
        downBorderColor: '#008F28',
        lineOption:{
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            }
          },
          grid: {
            left: '10%',
            right: '10%',
            bottom: '15%'
          },
          xAxis: {
            type: 'category',
            // data: ['2013/1/24','2013/1/25','2013/1/26','2013/1/27',
            //   '2013/1/28','2013/1/29','2013/1/30','2013/1/31'],
            data: [],
            scale: true,
            boundaryGap: false,
            axisLine: {onZero: false},
            splitLine: {show: false},
            splitNumber: 20,
            min: 'dataMin',
            max: 'dataMax'
          },
          yAxis: {
            scale: true,
            splitArea: {
              show: true
            }
          },
          dataZoom: [
            {
              type: 'inside',
              start: 50,
              end: 100
            },
            {
              show: true,
              type: 'slider',
              top: '90%',
              start: 50,
              end: 100
            }
          ],
          series: [
            {
              name: '',
              type: 'line',
              data: [],
              // data: [2320.26,2320.26,2287.3,2362.94,
              //   2300,2291.3,2288.26,2308.38],
              smooth: true,
              lineStyle: {
                opacity: 0.5
              }
            }
          ]
        },
        //查询
        sensorId: '',
        sensorChannel: '',
        positionId:'',
        channelId:'',
        deviceId:'',
        //时间查询
        dateTimerRange:[],
        pickerOptions: {
          shortcuts: [{
            text: '最近一天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近二天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近三天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        }

      };
    },
    watch: {
      //观察option的变化
      lineOption: {
        handler(newVal, oldVal) {
          if (this.myChart) {
            if (newVal) {
              this.myChart.setOption(newVal);
            } else {
              this.myChart.setOption(oldVal);
            }
          } else {
            this.initData();
          }
        },
        deep: true //对象内部属性的监听，关键。
      }
    },
    computed: {
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
    },
    mounted() {
    },
    methods: {
      nodeClick(data) {
        this.treeId = data.id;
        getDetail(this.treeId).then(res => {
          this.treeLevel = res.data.data.sensorType;
          if(this.treeLevel === 0){//设备
            this.showAcquisition = false;
            this.showPosition = false;
            this.showDevice = true;
            this.deviceId = res.data.data.channelId;
            this.handleDeviceDetail(res.data.data.channelId);
          }else if (this.treeLevel === 4){//测点
            this.showAcquisition = false;
            this.showPosition = true;
            this.showDevice = false;
            this.positionId = res.data.data.channelId;
            this.handlePositionDetail(res.data.data.channelId);
          }else { //传感器
            this.showAcquisition = true;
            this.showPosition = false;
            this.showDevice = false;
            this.radio = 2;
            this.showData = true;
            this.showProp = false;
            this.channelId = res.data.data.channelId;
            this.handleSensorDetail(res.data.data.channelId);
          }
        })
      },
      dateCreated() {
        //当前设定的日期时间
        this.dateTimerRange.push(dateFormat(new Date()))
        //前一天设定的日期时间
        let d = new Date
        d.setTime(d.getTime()-24*60*60*1000);
        this.dateTimerRange.unshift(dateFormat(d))
      },
      initData() {
        if (document.getElementById('myChartOnlineLine') == null) {
          return
        }
        this.$echarts.dispose(document.getElementById('myChartOnlineLine'))
        let myChartOnlineLine = this.$echarts.init(document.getElementById('myChartOnlineLine'))// 基于准备好的dom，初始化echarts实例
        myChartOnlineLine.setOption(this.lineOption,true);// 绘制图表
      },
      drawHistoryLine(){
        this.$nextTick(() => {
          this.initData()
        })
      },
      radioChange(val){
        if (val === "1"){
          this.showData = false;
          this.showProp = true;
        }else {
          this.showData = true;
          this.showProp = false;
          //this.drawHistoryLine();
        }
      },
      handleDeviceDetail(id){
        getDeviceDetail(id).then(res => {
          this.formDevice= res.data.data;
        })
      },
      handlePositionDetail(id){
        getPositionDetail(id).then(res => {
          this.formPosition= res.data.data;
        })
      },
      handleSensorDetail(id){
        getSensorDetail(id).then(res => {
          //初始化时间
          if (this.dateTimerRange.length ===0) {
            this.dateCreated();
          }
          this.formSensor = res.data.data;
          this.sensorId = res.data.data.id;
          this.sensorChannel = res.data.data.code;
          let params = {};
          if (this.dateTimerRange) {
            params = {
              startTime_datege: this.dateTimerRange[0],
              startTime_datelt: this.dateTimerRange[1],
              sensorId: res.data.data.id,
              sensorChannel: res.data.data.code
            };
          }else {
            params = {
              sensorId: res.data.data.id,
              sensorChannel: res.data.data.code
            };
          }
          //曲线
          this.handleAcquisitionOnLine(this.pageLine,params);
          //表格
          this.onLoad(this.pageTable,params)
        })
      },
      handleSensorDetailLine(id){
         getSensorDetail(id).then(res => {
          this.formSensor = res.data.data;
          this.sensorId = res.data.data.id;
          this.sensorChannel = res.data.data.code;
          const params = {
            sensorId: res.data.data.id,
            sensorChannel: res.data.data.code
          }
          //曲线
           this.handleAcquisitionOnLine(this.pageLine,params);
          //表格
           this.onLoad(this.pageTable,params)
        })
      },
      async handleAcquisitionOnLine(page,params = {}){
        let records = []
        let pages = 0
        await getAcquisitionOnLine(page.currentPage, page.pageSize,params).then(res => {
          const rec = res.data.data.records
          for (let j = 0; j< rec.length; j++) {
            records.push(rec[j])
          }
          pages = res.data.data.pages
        })
        if (pages > 1){
          for (let i = 2; i < pages +1; i++) {
            await getAcquisitionOnLine(i, page.pageSize,params).then(res => {
              const reco = res.data.data.records
              for (let k = 0; k< reco.length; k++) {
                records.push(reco[k])
              }
            })
          }
        }
        await this.splitData(records)
      },
      splitData(rawData) {
        let categoryData = [];
        let values = []
        for (let i = 0; i < rawData.length; i++) {
          categoryData.push(rawData[i].startTime);
          values.push(rawData[i].sampleValue);
        }
        this.lineOption.xAxis.data = categoryData
        this.lineOption.series[0].data = values
      },
      currentChange(currentPage){
        this.pageTable.currentPage = currentPage;
        let values = {};
        if (this.dateTimerRange) {
          values = {
            startTime_datege: this.dateTimerRange[0],
            startTime_datelt: this.dateTimerRange[1],
            sensorId: this.sensorId,
            sensorChannel: this.sensorChannel
          };
        }else {
          values = {
            sensorId: this.sensorId,
            sensorChannel: this.sensorChannel
          };
        }
        //表格
        this.onLoad(this.pageTable,values)
      },
      sizeChange(pageSize){
        this.pageTable.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.pageTable.total = data.total;
          this.dataTable = data.records;
          this.loading = false;
        });
      },
      searchData(values){
        //曲线
        this.handleAcquisitionOnLine(this.pageLine,values);
        //表格
        this.onLoad(this.pageTable,values)
      },
      searchDataRange(){
        let values = {};
        if (this.dateTimerRange) {
          values = {
            startTime_datege: this.dateTimerRange[0],
            startTime_datelt: this.dateTimerRange[1],
            sensorId: this.sensorId,
            sensorChannel: this.sensorChannel
          };
        }else {
          values = {
            sensorId: this.sensorId,
            sensorChannel: this.sensorChannel
          };
        }
        this.searchData(values)
      },
      onclickPosition(){
        if (this.treeLevel === 4){
          const id = this.positionId
          this.$router.push({path: `/work/stress/show/data/${id}`});
        }
      },
      onclickDevice(){
        if (this.treeLevel === 0){
          const id = this.deviceId
          this.$router.push({path: `/work/stress/show/line/${id}`});
        }
      }
    }
  };
</script>

<style>
  .box {
    height: 800px;
  }

  .el-scrollbar {
    height: 100%;
  }

  .box .el-scrollbar__wrap {
    overflow: scroll;
  }

  .outLogin{
    width: 36px;
    height:36px;
    float: right;
    margin-top: 15px;
    margin-right: 10px
  }
</style>
